import { defineStore } from 'pinia'
import { login as loginApi, getUserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 获得token
    token: localStorage.getItem('token') || '',
    //获得用户信息
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
    //获得用户角色
    role: localStorage.getItem('role') || ''
  }),
  
  getters: {
    isAdmin: (state) => state.role === 'admin',
    isUser: (state) => state.role === 'user',
    username: (state) => state.userInfo?.username || ''
  },
  
  actions: {
    async login(username, password) {
      try {
        const res = await loginApi(username, password)
        this.token = res.data.token
        this.userInfo = res.data.userInfo
        this.role = res.data.role
        // 存储token到本地
        localStorage.setItem('token', this.token)
        // 存储userInfo到本地
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        // 存储role到本地
        localStorage.setItem('role', this.role)
        
        return res
      } catch (error) {
        throw error
      }
    },
    
    async fetchUserInfo() {
      try {
        const res = await getUserInfo()
        this.userInfo = res.data
        this.role = res.data.role
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        localStorage.setItem('role', this.role)
      } catch (error) {
        this.logout()
        throw error
      }
    },
    
    logout() {
      this.token = ''
      this.userInfo = null
      this.role = ''
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('role')
    }
  }
})

